package com.project.school_flate.serviceimpl.shop;

import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.project.school_flate.dto.shop.ShopRuleDto;
import com.project.school_flate.entity.shop.ShopRule;
import com.project.school_flate.entity.shop.ShopRule;
import com.project.school_flate.entity.table.shop.ShopRuleTable;
import com.project.school_flate.mapper.shop.ShopRuleMapper;
import com.project.school_flate.service.shop.ShopRuleService;
import com.project.school_flate.util.PoToDTO;
import com.project.school_flate.util.Result.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  服务层实现。
 *
 * @author 马维健
 * @since 2024/1/2
 */
@Service
public class ShopRuleServiceImpl extends ServiceImpl<ShopRuleMapper, ShopRule> implements ShopRuleService {

    @Autowired
    private ShopRuleMapper oShopRuleMapper;

    /**
     * 获取店铺规则
     * @param oShopRuleDto
     * @return
     * @throws Exception
     */
    @Override
    public Result getShopRule(ShopRuleDto oShopRuleDto) throws Exception {
        List<ShopRule> oShopRuleList = new ArrayList<>();
        long total = 0;
        QueryWrapper queryWrapper = new QueryWrapper();
        //判断是否传入店铺ID
        if(StringUtils.isNotBlank(oShopRuleDto.getShopId())){
            queryWrapper.where(ShopRuleTable.SHOP_RULE.SHOP_ID.eq(oShopRuleDto.getShopId()));
        }
        //判断是否传入店铺规则类型
        if(oShopRuleDto.getType() != null){
            queryWrapper.where(ShopRuleTable.SHOP_RULE.TYPE.eq(oShopRuleDto.getType()));
        }
        queryWrapper.orderBy("type desc");
        //是否分页
        if(oShopRuleDto.getPage() != null && oShopRuleDto.getLimit() != null){
            Page<ShopRule> ShopRulePage = oShopRuleMapper.paginateWithRelations(oShopRuleDto.getPage(),oShopRuleDto.getLimit(),queryWrapper);
            oShopRuleList = ShopRulePage.getRecords();
            total = ShopRulePage.getTotalRow();
        }else{
            oShopRuleList = oShopRuleMapper.selectListWithRelationsByQuery(queryWrapper);
            total = oShopRuleList.size();
        }
        //PoToDto
        List<ShopRuleDto> oShopRuleDtoList = (List<ShopRuleDto>) PoToDTO.poToDtoList(oShopRuleList,new ShopRuleDto());
        return Result.ok(oShopRuleDtoList,total);
    }

    /**
     * 添加店铺规则
     * @param oShopRuleDto
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Result addShopRule(ShopRuleDto oShopRuleDto) throws Exception {
        ShopRule oShopRule = new ShopRule();
        PoToDTO.poToDto(oShopRuleDto,oShopRule);
        if(oShopRuleMapper.insert(oShopRule) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("添加店铺规则失败");
        }
        return Result.ok("添加店铺规则成功");
    }

    /**
     * 修改店铺规则
     * @param oShopRuleDto
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Result updateShopRule(ShopRuleDto oShopRuleDto) throws Exception {
        ShopRule oShopRule = new ShopRule();
        PoToDTO.poToDto(oShopRuleDto,oShopRule);
        if(oShopRuleMapper.update(oShopRule) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("修改店铺规则失败");
        }
        return Result.ok("修改店铺规则成功");
    }

    /**
     * 删除店铺规则
     * @param oShopRuleDto
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Result deleteShopRule(ShopRuleDto oShopRuleDto) throws Exception {
        ShopRule oShopRule = new ShopRule();
        PoToDTO.poToDto(oShopRuleDto,oShopRule);
        if(oShopRuleMapper.deleteById(oShopRule.getId()) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("删除店铺规则失败");
        }
        return Result.ok("删除店铺规则成功");
    }

    /**
     * 批量添加店铺规则
     * @param oShopRuleDto
     * @return
     * @throws Exception
     */
    @Override
    public Result batchAddShopRule(ShopRuleDto oShopRuleDto) throws Exception {
        //删除以前的店铺规则
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(ShopRuleTable.SHOP_RULE.SHOP_ID.eq(oShopRuleDto.getShopId()));
        queryWrapper.where(ShopRuleTable.SHOP_RULE.TYPE.in(0,1));
        oShopRuleMapper.deleteByQuery(queryWrapper);
        //创建满减MAP和储蓄MAP
        Map<Double,ShopRule> fullMap = new HashMap<>();
        Map<Double,ShopRule> saveMap = new HashMap<>();
        for(ShopRule oShopRule : oShopRuleDto.getShopRuleList()){
            oShopRule.setShopId(oShopRuleDto.getShopId());
            if(oShopRule.getType() == 1){
                if(fullMap.containsKey(oShopRule.getReachPrice())){
                    return Result.error("满减规则中有重复达到金额，无法添加");
                }else{
                    fullMap.put(oShopRule.getReachPrice(),oShopRule);
                }
            }
            if(oShopRule.getType() == 2){
                if(saveMap.containsKey(oShopRule.getReachPrice())){
                    return Result.error("储蓄规则中有重复达到金额，无法添加");
                }else{
                    saveMap.put(oShopRule.getReachPrice(),oShopRule);
                }
            }
        }
        if(oShopRuleMapper.insertBatch(oShopRuleDto.getShopRuleList()) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("添加店铺规则失败");
        }
        return Result.ok("添加店铺规则成功");
    }

    /**
     * 批量添加储蓄规则
     * @param oShopRuleDto
     * @return
     * @throws Exception
     */
    @Override
    public Result batchAddShopRuleToSave(ShopRuleDto oShopRuleDto) throws Exception {
        //删除以前的店铺规则
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(ShopRuleTable.SHOP_RULE.SHOP_ID.eq(oShopRuleDto.getShopId()));
        queryWrapper.where(ShopRuleTable.SHOP_RULE.TYPE.eq(2));
        oShopRuleMapper.deleteByQuery(queryWrapper);
        //创建map
        Map<Double,ShopRule> map = new HashMap<>();
        for(ShopRule oShopRule : oShopRuleDto.getShopRuleList()){
            oShopRule.setShopId(oShopRuleDto.getShopId());
            if(map.containsKey(oShopRule.getReachPrice())){
                return Result.error("储蓄规则中有重复达到金额，无法添加");
            }else{
                map.put(oShopRule.getReachPrice(),oShopRule);
            }
        }
        if(oShopRuleMapper.insertBatch(oShopRuleDto.getShopRuleList()) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("添加储蓄规则失败");
        }
        return Result.ok("添加储蓄规则成功");
    }

}
